<?php

class My_Acl{
    public function hasIdentity($request = null){
        $helper_redirector = new Zend_Controller_Action_Helper_Redirector();
        $auth = Zend_Auth::getInstance();
        
        $auth->setStorage(new Zend_Auth_Storage_Session('Zend_Auth_RPS')); 
        if(!$auth->hasIdentity()){
            $helper_redirector->gotoUrl('/default/auth');
        }else{
            $user = $auth->getIdentity();
            $modelUser = new Default_Model_User();
            $userCheck = $modelUser->getDataById($user['userId']);
            if($userCheck['sessionId'] != session_id()){
                $auth->clearIdentity();
                $helper_redirector->gotoUrl('/default/auth/index/type/login_other_computer');
                return false;
            }
        }
        
        //check quyền user
        $db = Zend_Db_Table::getDefaultAdapter();
        $user = $auth->getIdentity();
        $query = $db->select()
                    ->from(array('r'=>'role'), array('r.roleId', 'r.roleName','r.homepage','r.gameId','r.resourceId'))
                    ->join(array('ur'=>'user_role'),'r.roleId = ur.roleId', array('ur.userId'))
                    ->where('ur.userId = ?',(int)$user['userId']);
        $privilegeList   = $db->fetchAll($query);
        
        $roleList = array();
        foreach($privilegeList as $row){
            if(is_array($roleList) && is_array(json_decode($row['resourceId']))){
                $roleList = array_merge($roleList, json_decode($row['gameId']));
            }
        }
        if($roleList){
            $roleList = array_unique($roleList);
        }
        if(!$roleList){
            $helper_redirector->gotoUrl('/auth/logout');
        }
        return $auth;
    }
    public function checkViewUserInfo(){
        $helper_redirector = new Zend_Controller_Action_Helper_Redirector();
        $auth = Zend_Auth::getInstance();
        $request = Zend_Controller_Front::getInstance()->getRequest();
        
        $auth->setStorage(new Zend_Auth_Storage_Session('Zend_Auth_RPS')); 
        if ($this->hasIdentity()){
            $user       = $auth->getIdentity();
            $params     = $request->getParams();
            if(!isset($params['game'])){
                return false;
            }
            $db = Zend_Db_Table::getDefaultAdapter();
            $user = $auth->getIdentity();
            $query = $db->select()
                        ->from(array('r'=>'role'))
                        ->join(array('ur'=>'user_role'),'r.roleId = ur.roleId', array('ur.userId'))
                        ->where('ur.userId = ?',(int)$user['userId'])
                        ->where('r.gameId like (?)',"%\"{$params['game']}\"%");
            $privilegeList   = $db->fetchAll($query);
            $data = array('viewPhone'=>0,'viewEmail'=>0);
            foreach($privilegeList as $row){
                if($row['viewPhone'] == 1){
                    $data['viewPhone'] = 1;
                }
                if($row['viewEmail'] == 1){
                    $data['viewEmail'] = 1;
                }
                if($data['viewPhone'] == 1 && $data['viewEmail'] == 1){
                    break;
                }
            }
            return $data;
            
        }
        return false;
    }
    
    // kiem tra user duoc quyen truy cap tinh nang nay ko
    public function checkAllowed($request){
        $helper_redirector = new Zend_Controller_Action_Helper_Redirector();
        $auth = Zend_Auth::getInstance();
        
        $auth->setStorage(new Zend_Auth_Storage_Session('Zend_Auth_RPS')); 
        if ($this->hasIdentity()){
        
            //history
            //prTien($request->getParams());
            $params     = $request->getParams();
            $user       = $auth->getIdentity();
            $requestUri = $request->getRequestUri();
            $module     = $request->getModuleName();
            $controller = $request->getControllerName();
            $action     = $request->getActionName();
            if(isset($params['reload'])){
                $reload     = $params['reload'];
            }
            $data['userId']     = $user['userId'];
            $data['time']       = time();
            $data['url']        = $requestUri;
            $data['module']     = $module;
            $data['controller'] = $controller;
            $data['action']     = $action;
            if(file_exists(CONFIG_PATH . '/history.ini')){
                $configHistory = new Zend_Config_Ini(CONFIG_PATH . '/history.ini', APPLICATION_ENV);
                if(isset($configHistory->history->$data['module']->$data['controller']->$data['action']->obj)){
                    $data['obj'] = $configHistory->history->$data['module']->$data['controller']->$data['action']->obj;
                }elseif(isset($configHistory->history->$data['module']->$data['controller']->obj)){
                    $data['obj'] = $configHistory->history->$data['module']->$data['controller']->obj;
                }elseif(isset($configHistory->history->$data['module']->obj)){
                    $data['obj'] = $configHistory->history->$data['module']->obj;
                }
                /*
                if(isset($data['obj']) && $data['obj']){
                    if(isset($configHistory->obj->$data['obj']->objField)){
                        $data['objField'] = $configHistory->obj->$data['obj']->objField;
                    }
                }
                */
                if(isset($params['game'])){
                    $data['objField'] = $params['game'];
                    $data['objId'] = $params['game'];
                }
            }
            if($controller != 'history' && $action != 'edit' && $action != 'add' && $action != 'delete' && $action != 'cache' && $action != 'email' && $action != 'fill'){
                if(($controller != 'ccu-stats') || ($controller == 'ccu-stats' && !isset($reload))){
                    $modelHistory = new Admin_Model_History();
                    $modelHistory->addData($data);
                }
            }
            
            if(!$this->isAllowed($auth->getIdentity(), $request)){
                $helper_redirector->gotoUrl('/default/error/accessdenied');
            }
        }else{
            $helper_redirector->gotoUrl('/default/auth');
        }
        return $auth;
    }
    
    public function isAllowed($user, $request){
        $db = Zend_Db_Table::getDefaultAdapter();
        
        // lấy danh sách các resource của user 
        $query = $db->select()
                    ->from(array('p'=>'role'), array('p.roleId', 'p.gameId', 'p.resourceId'))
                    ->where('p.roleId IN (SELECT u.roleId FROM user_role u WHERE u.userId = '.$user['userId'].')');
        $privilegeList   = $db->fetchAll($query);
        $resourceTemp   = array();
        $gameTemp       = array();
        foreach($privilegeList as $row){
            $resourceTemp   = array_merge($resourceTemp, json_decode($row['resourceId']));
            $gameTemp       = array_merge($gameTemp, json_decode($row['gameId']));
        }
        $resourceTemp           = array_unique($resourceTemp);
        $resourceList           = array_values($resourceTemp);
        $gameTemp               = array_unique($gameTemp);
        $gameList               = array_values($gameTemp);
        
        // kiem tra co request xem trang game ko. 
        if($request->getModuleName() == 'default'){
            $game = $request->getParams();
            if(isset($game['game'])){
                if(!in_array($game['game'], $gameList)){
                    return false;
                }
            }else{
                return false;
            }
        }
        // kiểm tra request của user thuộc resource nào
        $module     = $request->getModuleName();
        $controller = $request->getControllerName();
        $action     = $request->getActionName();
        $query = $db->select()
                    ->from(array('r'=>'resource'), array('r.resourceId'))
                    ->where("r.menu = '$module/$controller/$action'");
        $resourceCheck = $db->fetchRow($query);
        
        // kiểm tra request của user có nằm trong danh sách các resource của user ko (kt có quyền thao tác trên request này ko)
        if(in_array($resourceCheck['resourceId'], $resourceList) || !isset($resourceCheck['resourceId']))
            return true;
        else
            return false;
    }
	
    // danh sach quyen cua user
	public function listAllowed($user, $gameId = 0){
        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        
        // Lấy danh sách các resource của user (json)
        if($gameId){
            $query = $db->select()
                        ->from(array('p'=>'role'), array('p.roleId', 'p.resourceId'))
                        ->where('p.gameId like "%'.$gameId.'%" AND p.roleId IN (SELECT u.roleId FROM user_role u WHERE u.userId = '.$user['userId'].')');
                   
            $resourceList = $db->fetchAll($query);
        }else{
            $query = $db->select()
                        ->from(array('p'=>'role'), array('p.roleId', 'p.resourceId'))
                        ->where('p.roleId IN (SELECT u.roleId FROM user_role u WHERE u.userId = '.$user['userId'].')');
                   
            $resourceList = $db->fetchAll($query);
        }
        $resourceTemp = array();
        foreach($resourceList as $row){
            $resourceTemp = array_merge($resourceTemp, json_decode($row['resourceId']));
        }
        $resourceTemp           = array_unique($resourceTemp);
        $resourceList           = array_values($resourceTemp);
        $resourceList           = json_encode($resourceList);
        $resourceList           = str_replace(array('[',']'), array('(',')'), $resourceList);
        //echo '<pre>',print_r($resourceList),'</pre>';exit;
        // Lấy danh sách các resource của user (record)
        $query = $db->select()
                    ->from(array('r'=>'resource'), array('r.resourceId','r.resourceName','r.moduleName','r.controllerName','r.actionName','r.menu'))
                    ->where('r.resourceId IN '.$resourceList)
                    ->order('r.ord ASC')
                    ->order('r.resourceId ASC');
                                 
		$row = $db->fetchAll($query);
		return $row;
    }
    
    // danh sach quyen cua user
	public function checkResource($user, $module, $controller, $action){
        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        
        // Lấy danh sách các resource của user (json)
        $query = $db->select()
                    ->from(array('p'=>'role'), array('p.roleId', 'p.resourceId'))
                    ->where('p.roleId IN (SELECT u.roleId FROM user_role u WHERE u.userId = '.$user['userId'].')');
        $resourceList = $db->fetchAll($query);
        $resourceTemp = array();
        foreach($resourceList as $row){
            $resourceTemp = array_merge($resourceTemp, json_decode($row['resourceId']));
        }
        $resourceTemp           = array_unique($resourceTemp);
        $resourceList           = array_values($resourceTemp);
        $resourceList           = json_encode($resourceList);
        $resourceList           = str_replace(array('[',']'), array('(',')'), $resourceList);
        //echo '<pre>',print_r($resourceList),'</pre>';exit;
        
        // Lấy danh sách các resource của user (record)
        $query = $db->select()
                    ->from(array('r'=>'resource'), array('r.resourceId','r.moduleName','r.controllerName','r.actionName'))
                    ->where('r.resourceId IN '.$resourceList)
                    #->where('r.menu = ?',"$module/$controller/$action")
                    ->where('r.moduleName = ?',$module)
                    ->where('r.controllerName = ?',$controller)
                    ->where('r.actionName = ?',$action);
                    
		$row = $db->fetchRow($query);
        if($row)
		  return true;
		return false;
    }
    
    // kiem tra chuc nang duoc bao tri hay khong
    public function checkRepair($request, $repair = ''){
        $helper_redirector = new Zend_Controller_Action_Helper_Redirector();
        $auth = Zend_Auth::getInstance();
        
        $module     = $request->getModuleName();
        $controller = $request->getControllerName();
        $action     = $request->getActionName();
        
        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        $query = $db->select()
                    ->from(array('r'=>'resource'), array('r.resourceId','r.moduleName','r.controllerName','r.actionName'))
                    #->where('r.menu = ?',"$module/$controller/$action")
                    ->where('r.moduleName = ?',$module)
                    ->where('r.controllerName = ?',$controller)
                    ->where('r.actionName = ?',$action);
                    
		$row = $db->fetchRow($query);
        
        if(!$row){
            return false;//khong bao tri
        }else{
            $repair = json_decode($repair);
            if(is_array($repair) && in_array($row['resourceId'], $repair)){
                return true;
            }else{
                return false;
            }
        }
        
    }
    
}
